package com.db_tenant.citus;

import lombok.extern.slf4j.Slf4j;
import org.avaje.datasource.DataSourceConfig;
import org.avaje.datasource.core.Factory;

import javax.sql.DataSource;

@Slf4j
public class WorkerTenant implements CitusTenant {

  private final DataSource dataSource;
  private final String tenantName = "CitusWorderTenant";

  public WorkerTenant(String jdbcUrl, String username, String password) {
    dataSource = open(jdbcUrl, username, password);
  }

  @Override
  public DataSource dataSource() {
    return dataSource;
  }

  private DataSource open(String jdbcUrl, String username, String password) {
    log.info("Create DataSource for tenantId: {} -> {}", getTenantName(), jdbcUrl);
    DataSourceConfig config = new DataSourceConfig();
    config.setDriver("org.postgresql.Driver");
    config.setUrl(jdbcUrl);
    config.setUsername(username);
    config.setPassword(password);
    config.setMaxConnections(1);
    config.setWaitTimeoutMillis(3000);
    return new Factory().createPool(getTenantName(), config);
  }

  String getTenantName() {
    return tenantName;
  }
}
